package com.sptpc.exam;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;

@WebServlet("/download.do")
public class DownloadServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String fileName = request.getParameter("filename");
        // 得到下载文件的位置
        String downloadPath = getServletContext().getRealPath("/download");
        // 完整的文件下载名
        String path = downloadPath + "/" + fileName;
        // 设置下载对应的response的header
        response.setHeader("Content-Disposition", "attachment;filename" + fileName);
        // 设置文件类型
        String mimeType = getServletContext().getMimeType(path);
        response.setContentType(mimeType);

        // 获得response输出流
        ServletOutputStream out = response.getOutputStream();
        // 获得针对文件的输入流
        FileInputStream fin = new FileInputStream(path);
        // 从文件读，写入response
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = fin.read(buffer))!=-1) {
            out.write(buffer, 0, len);
        }
        fin.close();
    }
}
